package cromosomas;

import java.text.DecimalFormat;

/**
 * class CromosomaF1
 * 
 * @author Marco Gallardo Casu, Miguel Cisneros Rojas
 * 
 */
public class CromosomaF4 extends Cromosoma {

	private double xMin = 0;
	private double xMax = 100;
	private int nVars;

	private int[] longitudes;

	public CromosomaF4(int nVars, double tolerancia) {
		this.nVars = nVars;
		longitudes = new int[nVars];
		this.longitud = 0;
		final int LENGTH = (int) Math
				.round(log2(1 + (xMax - xMin) / tolerancia));
		for (int index = 0; index < nVars; index++) {
			this.longitud += LENGTH;
			longitudes[index] = longitud;
		}
		this.fenotipo = new double[nVars];
		this.genes = generarGenes();
		this.tolerancia = tolerancia;
	}

	public CromosomaF4(int n, int longitud, double tolerancia) {
		this.longitud = longitud;
		this.nVars = n;
		this.genes = generarGenes();
		this.tolerancia = tolerancia;
	}

	public CromosomaF4(boolean[] genes, double tolerancia) {
		this.longitud = genes.length;
		this.genes = genes;
		this.tolerancia = tolerancia;
	}

	public double[] fenotipo() {
		fenotipo[0] = (xMax - xMin) * binDec(genes, 0, longitudes[0]);
		fenotipo[0] /= Math.pow(2, longitudes[0]) - 1;
		fenotipo[0] += xMin;
		for (int index = 1; index < nVars; index++) {
			fenotipo[index] = (xMax - xMin)
					* binDec(genes, longitudes[index - 1], longitudes[index]);
			fenotipo[index] /= Math.pow(2, longitudes[index]
					- longitudes[index - 1]) - 1;
			fenotipo[index] += xMin;
		}
		return fenotipo;
	}

	public double evalua() {
		return aptitud = -funcion(fenotipo());
	}

	protected double funcion(double[] x) {
		double ac = 0.0;
		for (int index = 0; index < nVars; index++) {
			double xi = x[index];
			ac += xi * Math.sin(Math.sqrt(Math.abs(xi)));
		}
		return -ac;
	}

	public double getTolerancia() {
		return tolerancia;
	}

	public void setTolerancia(double tolerancia) {
		this.tolerancia = tolerancia;
	}

	@Override
	protected String aptitudToString() {
		return (new DecimalFormat("#.######")).format(-aptitud);
	}

	@Override
	protected String genesToString() {
		String s = "";
		for (int i = 0; i < longitudes[0]; i++) {
			s += genes[i] ? "1" : "0";
		}
		if (nVars > 1) {
			s += " | ";
			for (int index = 1; index < nVars - 1; index++) {
				for (int i = longitudes[index - 1]; i < longitudes[index]; i++) {
					s += genes[i] ? "1" : "0";
				}
				s += " | ";
			}
			for (int i = longitudes[nVars - 2]; i < longitudes[nVars - 1]; i++) {
				s += genes[i] ? "1" : "0";
			}
		}
		return s;
	}

}
